package com.resifind.www.servlet.filter;

import com.alibaba.fastjson.JSON;
import com.resifind.www.constant.UserBanStatus;
import com.resifind.www.constant.UserTypes;
import com.resifind.www.dao.ClientDao;
import com.resifind.www.dao.MerchantDao;
import com.resifind.www.dao.impl.ClientDaoImpl;
import com.resifind.www.dao.impl.MerchantDaoImpl;
import com.resifind.www.exception.Resp;
import com.resifind.www.po.Client;
import com.resifind.www.po.Merchant;
import com.resifind.www.po.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author 36069
 */
@WebFilter({"/client/payOrder", "/client/orderRoom", "/client/recharge", "/client/fetchFavour"})
public class UserBanFilter implements Filter {
    private final MerchantDao merchantDao = new MerchantDaoImpl();
    private final ClientDao clientDao = new ClientDaoImpl();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        User user = (User) req.getSession().getAttribute("user");
        Object object = req.getSession().getAttribute("addition");
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/login.html");
        } else {
            //判断是客户端还是商户端
            if (user.getUserType().equals(UserTypes.MERCHANT)) {
                Merchant merchant = (Merchant) object;
                //判断用户是否被封禁
                merchant = merchantDao.queryMerchantByMerchantId(merchant.getId());
                if (UserBanStatus.BAN.equals(merchant.getApplicationStatus())) {
                    Resp<String> error = Resp.error(400, "已被封禁");
                    resp.getWriter().write(JSON.toJSONString(error));
                    return;
                }
            } else {
                Client client = (Client) object;
                //判断用户是否被封禁
                client = clientDao.queryClientByClientId(client.getId());
                if (UserBanStatus.BAN.equals(client.getStatus())) {
                    Resp<String> error = Resp.error(400, "已被封禁");
                    resp.getWriter().write(JSON.toJSONString(error));
                    return;
                }
            }
            chain.doFilter(request, response);
        }
    }
}